import java.io.*;

/**
 * 一、OutputStreamWrite
 * OutputStreamWrite(OutputStream out)
 * OutputStreamWrite(OutputStream out, String charsetName)
 * 是字符流通向字节流的桥梁：可使用charset将要写入流中的字符编码成字节
 * - void write(int c) 写入单个字符。
 * - void write(char[] cbuf)写入字符数组。
 * - abstract  void write(char[] cbuf, int off, int len)写入字符数组的某一部分,off数组的开始索引,len写的字符个数。
 * - void write(String str)写入字符串。
 * - void write(String str, int off, int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
 * - void flush()刷新该流的缓冲。
 * - void close() 关闭此流，但要先刷新它。
 *
 * 二、OutputStreamReader
 * OutputStreamReader(InputStream in)
 * OutputStreamReader(InputStream in, String charsetName)
 */
public class OutputStreamDemo {
    public static void main(String[] args) {
        try{
//            test1Write();
//            test2Reader();
            test3_gbk_to_utf8();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void test1Write() throws IOException{
        OutputStreamWriter osw1 = new OutputStreamWriter(new FileOutputStream("gbk.txt"),"GBK");
        osw1.write("玄烨，胤禛");
        osw1.flush();
        osw1.close();

        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("utf_8.txt")); // 默认为utf-8
        osw2.write("周星驰");
        osw2.flush();
        osw2.close();
    }

    public static void test2Reader() throws IOException{
        InputStreamReader isr1 = new InputStreamReader(new FileInputStream("gbk.txt"),"GBK");
        int len = -1;
        while (true){
            len = isr1.read();
            if(-1 == len){
                break;
            }
            System.out.println((char)len);
        }
        isr1.close();

        InputStreamReader isr2 = new InputStreamReader(new FileInputStream("utf_8.txt"));
        len = -1;
        while (true){
            len = isr2.read();
            if(-1 == len){
                break;
            }
            System.out.println((char)len);
        }
        isr2.close();
    }

    public static void test3_gbk_to_utf8() throws IOException{
        InputStreamReader isr = new InputStreamReader(new FileInputStream("gbk.txt"), "GBK");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("utf_8_cp.txt"), "UTF-8");

        int len = 0;
        while(true){
            len = isr.read();
            if(-1 == len){
                break;
            }
            osw.write(len);
        }

        osw.flush();
        osw.close();
        isr.close();
    }
}
